package com.xiaoyudeguang.apt;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class MapperGenerator {

    private final Filer filer;
    private final Messager messager;
    private final Configuration freemarkerConfig;
    private final Map<String, String> options;

    public MapperGenerator(Filer filer, Messager messager, Map<String, String> options) {
        this.filer = filer;
        this.messager = messager;
        this.options = options;
        this.freemarkerConfig = initFreemarkerConfig();
    }

    private Configuration initFreemarkerConfig() {
        Configuration config = new Configuration(Configuration.VERSION_2_3_31);
        config.setClassForTemplateLoading(getClass(), "/templates");
        config.setDefaultEncoding("UTF-8");
        return config;
    }

    public void generate(EntityInfo entityInfo) throws IOException, TemplateException {
        // 创建Java文件
        JavaFileObject jfo = filer.createSourceFile(entityInfo.getMapperFullClassName());
        // 准备模板数据
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("entityInfo", entityInfo);
        dataModel.put("useCache", Boolean.parseBoolean(options.getOrDefault("mapper.useCache", "false")));
        dataModel.put("customMethods", parseCustomMethods(options.get("mapper.customMethods")));

        // 获取模板并渲染
        Template template = freemarkerConfig.getTemplate("MapperInterface.java.ftl");
        try (Writer writer = jfo.openWriter()) {
            template.process(dataModel, writer);
        }
    }

    private Properties parseCustomMethods(String customMethodsProp) {
        Properties properties = new Properties();
        if (customMethodsProp != null && !customMethodsProp.isEmpty()) {
            try {
                properties.load(new java.io.ByteArrayInputStream(customMethodsProp.getBytes()));
            } catch (IOException e) {
                // 忽略错误
            }
        }
        return properties;
    }
}    